package com.xiaobai.common.utils.tool;

import com.alibaba.fastjson.JSONObject;
import com.xiaobai.common.utils.result.Result;
import jakarta.servlet.ServletContext;
import jakarta.servlet.ServletOutputStream;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

/**
 * HTTP返回工具
 */
public class HttpResponseUtils {

    private static Logger logger = LoggerFactory.getLogger(HttpResponseUtils.class);

    /**
     * 返回JSON数据
     *
     * @param result 返回数据
     * @param response
     * @throws IOException
     */
    public static void responseJson (Result result, HttpServletResponse response) throws IOException {
        response.setHeader("Content-type", "text/html;charset=UTF-8");
        response.setContentType(CommonConstants.APPLICATION_JSON_VALUE);
        response.getWriter().write(JSONObject.toJSONString(result));
    }

    /**
     * 返回文件流，用于文件下载
     *
     * @param inputStream 需要返回的文件流
     * @param fileName 文件名称
     * @param response
     */
    public static void responseFile(InputStream inputStream, String fileName, HttpServletRequest request, HttpServletResponse response) {
        try {
            if (inputStream == null) {
                logger.warn("返回文件为空！");
                return;
            }
            // 通过ServletContext获取类型
            ServletContext context = request.getServletContext();
            response.setContentType(context.getMimeType(fileName));
            response.addHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(fileName, StandardCharsets.UTF_8.name()));
            ServletOutputStream outputStream = response.getOutputStream();
            byte[] b = new byte[1024];
            int len;
            //从输入流中读取一定数量的字节，并将其存储在缓冲区字节数组中，读到末尾返回-1
            while ((len = inputStream.read(b)) > 0) {
                outputStream.write(b, 0, len);
            }
            inputStream.close();
        } catch (Exception e) {
            logger.error("文件流返回失败！", e);
        }
    }
}